package web

import (
	"fmt"
	"net/http"

	regexp "github.com/dlclark/regexp2"
	"github.com/gin-gonic/gin"

)

//userhandler 用户有关路由

type UserHandler struct {
	emailRegexExp    *regexp.Regexp
	passwordRegexExp *regexp.Regexp
}

func NewUserHandler() *UserHandler {
	const (
		emailRegexPattern    = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"
		passwordRegexPattern = `^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$`
	)
	emailExp, err := regexp.Compile(emailRegexPattern, regexp.None)
	if err != nil {
		// 处理编译正则表达式错误
		panic(err)
	}
	passwordExp, err := regexp.Compile(passwordRegexPattern, regexp.None)
	if err != nil {
		// 处理编译正则表达式错误
		panic(err)
	}
	return &UserHandler{
		emailRegexExp:    emailExp,
		passwordRegexExp: passwordExp,
	}
}
func (u *UserHandler) RegisterRoutes(server *gin.Engine) {
	ug := server.Group("/users")
	ug.GET("/profile", u.Profile)
	ug.POST("/edit", u.Edit)
	ug.POST("/login", u.Login)
	ug.POST("/signup", u.SignUp)
}

// SignUp 用户注册
func (u *UserHandler) SignUp(ctx *gin.Context) {
	type SignUpReq struct {
		Email           string `json:"email"`
		ConfirmPassword string `json:"confirmPassword"`
		Password        string `json:"password"`
	}
	var req SignUpReq
	if err := ctx.Bind(&req); err != nil {
		ctx.String(http.StatusBadRequest, "invalid request")
		return
	}
	if req.Email == "" || req.Password == "" || req.ConfirmPassword == "" {
		ctx.String(http.StatusBadRequest, "邮箱、密码和确认密码不能为空")
		return
	}

	isEmail, err := u.emailRegexExp.MatchString(req.Email)
	if err != nil {
		ctx.String(http.StatusInternalServerError, "系统错误")
		return
	}
	if !isEmail {
		ctx.String(http.StatusBadRequest, "邮箱格式错误")
		return
	}

	isPassword, err := u.passwordRegexExp.MatchString(req.Password)
	if err != nil {
		ctx.String(http.StatusInternalServerError, "系统错误")
		return
	}
	if !isPassword {
		ctx.String(http.StatusBadRequest, "密码必须大于8位包含数字特殊字符")
		return
	}
	if req.Password != req.ConfirmPassword {
		ctx.String(http.StatusBadRequest, "两次密码不一致")
		return
	}
	ctx.String(http.StatusOK, "注册成功")
	fmt.Printf("req:%+v\n", req)
	//ctx.String(http.StatusOK,"hello,signup")
}

// Login 用户登录
func (u *UserHandler) Login(ctx *gin.Context) {

}

// Profile 用户信息
func (u *UserHandler) Profile(ctx *gin.Context) {

}

// Edit 用户编辑
func (u *UserHandler) Edit(ctx *gin.Context) {

}
